from flask import Blueprint

from controllers import R
from mauth import HasPerm
from models.schema_group import SchemaGroup
from services.schema_group_service import SchemaGroupService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.schema_group_validator import SchemaGroupForm

# 声明一个蓝图
schema_group = Blueprint("schema_group", __name__, url_prefix="/dev/schemaGroup")

# 声明一个模型分组业务服务
schema_group_service = SchemaGroupService(model=SchemaGroup)


@schema_group.route("/detail", methods=["POST"])
@HasPerm(access="dev:schemaGroup:detail", name="通过id获取模型分组信息")
def schema_group_detail():
    """
    通过id获取模型分组信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = SchemaGroup.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = schema_group_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@schema_group.route("/page", methods=["POST"])
@HasPerm(access="dev:schemaGroup:page", name="分页查询模型分组列表")
def schema_group_page():
    """
    分页查询模型分组列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(schema_group_service.page(form))


@schema_group.route("/save", methods=["POST"])
@HasPerm(access="dev:schemaGroup:save", name="添加模型分组")
def schema_group_save():
    """
    添加模型分组
    :return:
    """
    form = SchemaGroupForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_group_service.save(form)
    return R.success("添加模型分组成功")


@schema_group.route("/update", methods=["POST"])
@HasPerm(access="dev:schemaGroup:update", name="修改模型分组")
def schema_group_update():
    """
    修改模型分组
    :return:
    """
    form = SchemaGroupForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_group_service.update(form)
    return R.success("修改模型分组成功")


@schema_group.route("/remove", methods=["POST"])
@HasPerm(access="dev:schemaGroup:remove", name="删除模型分组")
def schema_group_remove():
    """
    删除模型分组
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_group_service.remove(form)
    return R.success("删除模型分组成功")
